package org.witsoft.dtx.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.witsoft.dtx.service.TransactionManageService;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author XiaoQing Lin
 * @date 2020-09-21 11:11
 */
@Slf4j
public class TransactionManageScheduler {

    @Autowired
    private TransactionManageService transactionManageService;

    private ScheduledExecutorService releaseExecutor;

    private ScheduledExecutorService taskExecutor;

    public void start()  {
        releaseExecutor = new ScheduledThreadPoolExecutor(1);
        taskExecutor = new ScheduledThreadPoolExecutor(1);
        // 释放超时事务分支锁
        releaseExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    transactionManageService.releaseLockTimeout();
                }catch (Exception ex){
                    log.warn("事务释放超时错误:{}", "", ex);
                }
            }
        }, 1, 2, TimeUnit.MINUTES);
        // 准备取消-已确认的分支事务
        releaseExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    transactionManageService.updateConfirmedToPrepare();;
                }catch (Exception ex){
                    log.warn("事务更新为就绪状态错误:{}", "", ex);
                }
            }
        }, 1, 30, TimeUnit.SECONDS);
        // 确认或取消事务分支
        taskExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    transactionManageService.handle(100);
                }catch (Exception ex){
                    log.warn("事务执行错误:{}", "", ex);
                }
            }
        }, 0, 1, TimeUnit.SECONDS);
    }

    public void shutdown(){
        releaseExecutor.shutdown();
        taskExecutor.shutdown();
    }
}
